package Queue;

public class LoopQueue<E> implements Queue<E> {


    //数据长度 但是有一个单位被浪费了
    private E[] data;

    //对首
    private int front;

    //队尾
    private int tail;

    //元素个数
    private int size;


    public LoopQueue(int capacity) {
        this.data = (E[]) new Object[capacity + 1];
        front = 0;
        tail = 0;
        size = 0;
    }

    public LoopQueue() {
        this(10);
    }

    public int getSize() {
        return size;
    }

    public void enqueue(E e) {
        //判断队列是否是满的
        if ((tail + 1) % data.length == front) {
            resize(getCapacity() * 2);
        }
        data[tail] = e;
        tail = (tail + 1) % data.length;
        size++;
    }


    private void resize(int capacity) {
        E[] newData = (E[]) new Object[capacity + 1];

        //存在size个元素
        for (int i = 0; i < size; i++) {
            newData[i] = data[(i + front) % data.length];
        }
        data = newData;
        front = 0;
        //扩容之后的元素个数不会变
        tail = size;
    }


    public E dequeue() {
        if (isEmpty()) {
            throw new IllegalArgumentException("Cannot dequeue from empty queue.");
        }
        E e = data[front];
        data[front] = null;
        front = (front + 1) % data.length;
        size--;

        if (size == getCapacity() / 4 && getCapacity() / 2 != 0) {
            resize(getCapacity() / 2);
        }
        return e;
    }

    public E getFront() {
        if (isEmpty()) {
            throw new IllegalArgumentException("Queue is Empty!");
        }

        return data[front];
    }


    public boolean isEmpty() {
        return front == tail;
    }

    public int getCapacity() {
        return data.length - 1;
    }


    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append(String.format("Queue : size = %d ,capacity = %d \n", size, getCapacity()));
        builder.append("front [ ");
        for (int i = front; i != tail; i = (i + 1) % data.length) {
            builder.append(data[i]);
            if ((i + 1) % data.length != tail) {
                builder.append(",");
            }
        }
        builder.append(" ]  tail");
        return builder.toString();
    }


    public static void main(String[] args) {
       LoopQueue<Integer> queue = new LoopQueue<Integer>();
        for (int i = 0; i < 20; i++) {
            queue.enqueue(i);
            if (i % 3 == 2) {
                queue.dequeue();
            }
            System.out.println(queue);
        }

    }
}
